package com.shuai.jit.security.security;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * <p>
 * t密码的处理方法类型
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
@Component
@Slf4j
public class DefaultPasswordEncoder implements PasswordEncoder {

    @Autowired
    RedisTemplate redisTemplate;

    public DefaultPasswordEncoder() {
        this(-1);
    }

    /**
     * @param strength
     *            the log rounds to use, between 4 and 31
     */
    public DefaultPasswordEncoder(int strength) {

    }

    @Override
    public String encode(CharSequence rawPassword) {

        return new BCryptPasswordEncoder().encode(rawPassword);
    }

    /**
     * 判断两个密码是否相同
     * @param rawPassword   前端传过来的密码  123456
     * @param encodedPassword  后端传过来的 加密密码
     * @return
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        // 从redis 中获取盐的信息
        String salt=(String) redisTemplate.opsForValue().get(encodedPassword);
        return encoder.matches(rawPassword+salt,encodedPassword);
    }

    /**
     * 设置盐
     * @param rawPassword  没有加密的密码
     * @param encodedPassword 加密后的密码
     * @param salt 盐
     * @return 密码匹配成功，返回true
     */
//    public boolean matches(CharSequence rawPassword, String encodedPassword,String salt) {
//        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
//        // 获取盐
////        String salt=(String) redisTemplate.opsForValue().get(encodedPassword);
//        //  log.info(String.valueOf(encoder.matches(rawPassword+salt,encodedPassword)));
//        return encoder.matches(rawPassword+salt,encodedPassword);
//    }
}